package leetcode.editor.cn;

import java.util.Deque;
import java.util.LinkedList;

public class _32_LongestValidParentheses {
    public static void main(String[] args) {
        Solution solution = new _32_LongestValidParentheses().new Solution();
        int i = solution.longestValidParentheses("()(())");
        System.out.println(i);
    }


    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        // 动态规划解法
        public int longestValidParentheses1(String s) {
            int res = 0;
            int[] dp = new int[s.length()];
            for (int i = 1; i < s.length(); i++) {
                if (s.charAt(i) == ')') {
                    if (s.charAt(i - 1) == '(') {
                        dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
                    } else if (s.charAt(i) == ')') {
                        if ((i - dp[i - 1] - 1) >= 0 && s.charAt(i - dp[i - 1] - 1) == '(') {
                            dp[i] = dp[i - 1] + 2 + (i - dp[i - 1] - 2 >= 0 ? dp[i - dp[i - 1] - 2] : 0);
                        }
                    }
                    res = Math.max(res, dp[i]);
                }
            }
            return res;
        }

        //
        public int longestValidParentheses(String s) {
            int res = 0;
            Deque<Integer> stack = new LinkedList<>();
            stack.push(-1);
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '(') {
                    stack.push(i);
                } else if (s.charAt(i) == ')') {
                    stack.pop();
                    if (stack.isEmpty()) {
                        stack.push(i);
                    } else {
                        res = Math.max(res, i - stack.peek());
                    }
                }
            }
            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}